﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Microsoft.SharePoint;

namespace COSL_Initial
{
    class Program
    {
        static void Main(string[] args)
        {
            COSLInitial coslInitial = new COSLInitial();
            coslInitial.InitialCOSL();
        }
    }

    class COSLInitial
    {
        public void InitialCOSL()
        {
            try
            {
                const string siteUrl = "http://win-lfad8okund5/sites/COSL_Ticket/";
                if (CheckRootSiteExist(siteUrl))
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite site = new SPSite(siteUrl))
                        {
                            using (SPWeb web = site.RootWeb)
                            {
                                //Create User & Group
                                CreateUserAndGroup(web);

                                //Create List
                                //1.1.1	事业部信息（SP列表）BranchInformation
                                EnsureBranchInformation(web);
                                //1.1.2	部门信息（SP列表）DepartmentInformation
                                EnsureDepartmentInformation(web);
                                //1.1.12 导航信息（SP列表）NavigationInformation
                                EnsureNavigationInformation(web);
                                //1.1.11	黑名单（SP列表）BranchInformation
                                EnsureBlockList(web);
                            }
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Huston we have got problem!");
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                Console.WriteLine("Done!");
                Console.ReadLine();
            }
        }

        #region Create List
        //1.1.1	事业部信息（SP列表）BranchInformation
        private void EnsureBranchInformation(SPWeb web)
        {
            SPList list = web.EnsureList("事业部信息", "事业部信息", SPListTemplateType.GenericList);

            //Title	事业部名称	单行文本	BranchName
            list.Fields[SPBuiltInFieldId.Title].TitleResource.SetValueForUICulture(new CultureInfo(2052), "事业部名称");
            list.Fields[SPBuiltInFieldId.Title].Update();
            list.Fields[SPBuiltInFieldId.LinkTitle].TitleResource.SetValueForUICulture(new CultureInfo(2052), "事业部名称");
            list.Fields[SPBuiltInFieldId.LinkTitle].Update();
            list.Fields[SPBuiltInFieldId.LinkTitleNoMenu].TitleResource.SetValueForUICulture(new CultureInfo(2052), "事业部名称");
            list.Fields[SPBuiltInFieldId.LinkTitleNoMenu].Update();

            //TicketCenterMember	票务中心人员	人员和组	
            list.EnsureField("票务中心人员", "票务中心人员", SPFieldType.User, true);

            list.Update();
        }

        //1.1.2	部门信息（SP列表）DepartmentInformation
        private void EnsureDepartmentInformation(SPWeb web)
        {
            SPList list = web.EnsureList("部门信息", "部门信息", SPListTemplateType.GenericList);

            //Title	部门名称	单行文本	DepartmentName
            list.Fields[SPBuiltInFieldId.Title].TitleResource.SetValueForUICulture(new CultureInfo(2052), "部门名称");
            list.Fields[SPBuiltInFieldId.Title].Update();
            list.Fields[SPBuiltInFieldId.LinkTitle].TitleResource.SetValueForUICulture(new CultureInfo(2052), "部门名称");
            list.Fields[SPBuiltInFieldId.LinkTitle].Update();
            list.Fields[SPBuiltInFieldId.LinkTitleNoMenu].TitleResource.SetValueForUICulture(new CultureInfo(2052), "部门名称");
            list.Fields[SPBuiltInFieldId.LinkTitleNoMenu].Update();

            //BranchName	所属事业部	单行文本	单行文本
            list.EnsureField("所属事业部", "所属事业部", SPFieldType.Text, true);
            //Operator	经办人	人员和组	Username
            list.EnsureField("经办人", "经办人", SPFieldType.User, true);
            //Operator Mobile	经办人手机	单行文本	必填
            list.EnsureField("经办人手机", "经办人手机", SPFieldType.Text, true);
            //Approver	审批人	人员和组	Username
            list.EnsureField("审批人", "审批人", SPFieldType.User, true);
            //ApproverMail	审批人邮箱	单行文本	必填
            list.EnsureField("审批人邮箱", "审批人邮箱", SPFieldType.Text, true);
            //ESignature	电子签名	图片	
            list.EnsureField("电子签名", "电子签名", SPFieldType.URL, false);
            //ApprovalRequired	是否需要审批	是/否	
            list.EnsureField("是否需要审批", "是否需要审批", SPFieldType.Boolean, false);

            list.Update();
        }

        //1.1.12 导航信息（SP列表）NavigationInformation
        private void EnsureNavigationInformation(SPWeb web)
        {
            SPList list = web.EnsureList("导航信息", "导航信息", SPListTemplateType.GenericList);
            //Title	标题	单行文本	
            //Scope	访问范围	选项	经办人|票务中心
            SPFieldMultiChoice scopeField =
                (SPFieldMultiChoice)list.EnsureField("访问范围", "访问范围", SPFieldType.MultiChoice, true);
            scopeField.Choices.Clear();
            scopeField.Choices.Add("经办人");
            scopeField.Choices.Add("票务中心");
            scopeField.Update(false);
            //Links	链接	链接	
            list.EnsureField("链接", "链接", SPFieldType.URL, true);
            //ParentLinks	父节点	查阅项
            if (!list.Fields.ContainsField("父节点"))
            {
                list.Fields.AddLookup("父节点", list.ID, false);
                SPFieldLookup lookupField = (SPFieldLookup)list.Fields["父节点"];
                lookupField.LookupField = "标题";
                lookupField.Update();
            }

            //SequenceNumber	序号	数字
            list.EnsureField("序号", "序号", SPFieldType.Number, true);

            list.Update();
        }

        //1.1.11	黑名单（SP列表）BranchInformation
        private void EnsureBlockList(SPWeb web)
        {
            SPList list = web.EnsureList("黑名单", "黑名单", SPListTemplateType.GenericList);

            //Title	事业部名称	单行文本	BranchName
            list.Fields[SPBuiltInFieldId.Title].TitleResource.SetValueForUICulture(new CultureInfo(2052), "提醒文字");
            list.Fields[SPBuiltInFieldId.Title].Update();
            list.Fields[SPBuiltInFieldId.LinkTitle].TitleResource.SetValueForUICulture(new CultureInfo(2052), "提醒文字");
            list.Fields[SPBuiltInFieldId.LinkTitle].Update();
            list.Fields[SPBuiltInFieldId.LinkTitleNoMenu].TitleResource.SetValueForUICulture(new CultureInfo(2052), "提醒文字");
            list.Fields[SPBuiltInFieldId.LinkTitleNoMenu].Update();

            //TicketCenterMember	票务中心人员	人员和组	
            list.EnsureField("经办人", "经办人", SPFieldType.User, true);

            list.Update();
        }
        #endregion

        private void CreateUserAndGroup(SPWeb web)
        {
            //Ensure User & Group
            string[] groupNames = new[] { "经办人", "审批人", "票务中心" };
            //GroupExistsInSiteCollection
            foreach (var groupName in groupNames)
            {
                if (!GroupExistsInSiteCollection(web, groupName))
                {
                    //Add the group to the SPWeb web
                    web.SiteGroups.Add(groupName, web.SiteAdministrators[0], web.SiteAdministrators[0], groupName);
                    //Associate de group to the SPWeb. Now it will display in the quick launch bar
                    web.AssociatedGroups.Add(web.SiteGroups[groupName]);
                    web.Update();

                }
                //Assignment of the roles. 
                SPRoleAssignment assignment = new SPRoleAssignment((SPPrincipal)web.SiteGroups[groupName]);
                SPRoleDefinition roleApp = web.RoleDefinitions["读取"];
                assignment.RoleDefinitionBindings.Add(roleApp);
                web.RoleAssignments.Add(assignment);
                web.Update();
            }
        }

        private bool CheckRootSiteExist(string siteUrl)
        {
            bool exist = false;
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                Uri uri = new Uri(siteUrl);
                //Check WebApplication
                if (SPSite.Exists(uri))
                {
                    exist = true;
                }
            });
            return exist;
        }

        private bool GroupExistsInWebSite(SPWeb web, string name)
        {
            return web.Groups.OfType<SPGroup>().Count(g => g.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)) > 0;
        }
        private bool GroupExistsInSiteCollection(SPWeb web, string name)
        {
            return web.SiteGroups.OfType<SPGroup>().Count(g => g.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)) > 0;
        }
    }
}
